package com.yxkj.syh.app.huarong.activities;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.immersionbar.ImmersionBar;
import com.syh.app.basic.base.BaseActivity;
import com.syh.app.basic.base.BaseFragment;
import com.syh.app.basic.bean.LiveDataEvent;
import com.syh.app.basic.config.BasicConstants;
import com.syh.app.basic.utils.ActivityManager;
import com.syh.app.basic.utils.ComUtil;
import com.syh.app.basic.utils.Loog;
import com.syh.app.basic.utils.PermissionUtil;
import com.syh.app.basic.utils.Tooast;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yxkj.syh.app.huarong.BR;
import com.yxkj.syh.app.huarong.R;
import com.yxkj.syh.app.huarong.activities.creat.edit.EditOrderActivity;
import com.yxkj.syh.app.huarong.activities.msg.MsgListActivity;
import com.yxkj.syh.app.huarong.activities.orders.OrdersFragment;
import com.yxkj.syh.app.huarong.activities.orders.pay_list.PayOrdersFragment;
import com.yxkj.syh.app.huarong.activities.scan.ScanActivity;
import com.yxkj.syh.app.huarong.bean.DriveUser;
import com.yxkj.syh.app.huarong.bean.OrderInfo;
import com.yxkj.syh.app.huarong.constants.ArouterPath;
import com.yxkj.syh.app.huarong.databinding.ActivityMainBinding;
import com.yxkj.syh.app.huarong.util.PhotoUtil;
import com.yxkj.syh.app.huarong.util.UserManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

@Route(path = ArouterPath.MAIN_ACTIVITY)
public class MainActivity extends BaseActivity<ActivityMainBinding, MainVM> {

    private static final int PERMISSION_IMAGE = 0xb12;

    private BaseFragment mCurrentFragment;
    private OrdersFragment mOrdersFragment;
    private PayOrdersFragment mPayOrdersFragment;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected int getViewModelId() {
        return BR.mainVM;
    }

    @Override
    protected boolean needImmersionBarInit() {
        ImmersionBar.with(this).fitsSystemWindows(true).statusBarColor(R.color.defaultBlue).init();
        return false;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mOrdersFragment = OrdersFragment.newInstance();
        mPayOrdersFragment = PayOrdersFragment.newInstance();

        switchFragment(mOrdersFragment);

        mVDBinding.rgType.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rbOrders) {
                switchFragment(mOrdersFragment);
            } else if (checkedId == R.id.rbPayOrders) {
                switchFragment(mPayOrdersFragment);
            }
        });

        mVDBinding.flMsg.setOnClickListener(v -> startActivity(new Intent(MainActivity.this, MsgListActivity.class)));
        mVDBinding.flSetting.setOnClickListener(v -> ARouter.getInstance().build(ArouterPath.SETTING_ACTIVITY).navigation());
        mVDBinding.llFache.setOnClickListener(v -> {
            if (UserManager.getUserManager().getUser().getEmpId().equals(BasicConstants.WAIDIAOSIJI_EMPID)) {//外调司机
                ARouter.getInstance().build(ArouterPath.NEW_OUT_ORDER_ACTIVITY).withBoolean("isEmptyCar", false).navigation();
            } else {//自营司机
                new AlertDialog.Builder(MainActivity.this).setMessage("是否为空车？")
                        .setNegativeButton("是", (dialog, which) -> {
                            DriveUser user = UserManager.getUserManager().getUser();
                            if (user.getEmpId() == BasicConstants.WAIDIAOSIJI_EMPID) {
                                ARouter.getInstance().build(ArouterPath.NEW_OUT_ORDER_ACTIVITY).withBoolean("isEmptyCar", true).navigation();
                            } else {
                                ARouter.getInstance().build(ArouterPath.NEW_ORDER_ACTIVITY).withBoolean("isEmptyCar", true).navigation();
                            }
                        }).setPositiveButton("不是", (dialog, which) -> {
                    DriveUser user = UserManager.getUserManager().getUser();
                    if (user.getEmpId() == BasicConstants.WAIDIAOSIJI_EMPID) {
                        ARouter.getInstance().build(ArouterPath.NEW_OUT_ORDER_ACTIVITY).withBoolean("isEmptyCar", false).navigation();
                    } else {
                        ARouter.getInstance().build(ArouterPath.NEW_ORDER_ACTIVITY).withBoolean("isEmptyCar", false).navigation();
                    }
                }).create().show();
            }


        });
        mVDBinding.llQuickFache.setOnClickListener(v -> {
            AndPermission.with(MainActivity.this).requestCode(PERMISSION_IMAGE)
                    .permission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .callback(mPermissionListener).start();
        });
    }

    @Override
    protected void initData() {
        super.initData();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initObservers() {
        super.initObservers();
        mViewModel.mldScanCreatOrder.observe(this, orderInfo -> {
            ARouter.getInstance().build(ArouterPath.NEW_ORDER_ACTIVITY).withSerializable("preOrderInfo", orderInfo).navigation();
        });
    }

    private void switchFragment(final BaseFragment targetFragment) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        if (!targetFragment.isAdded() && null == fm.findFragmentByTag(targetFragment.getClass().getSimpleName())) {
            if (mCurrentFragment != null) {
                transaction.hide(mCurrentFragment);
            }
            transaction.add(R.id.flContent, targetFragment, targetFragment.getClass().getSimpleName());
        } else {
            if (targetFragment == mCurrentFragment) return;
            transaction.hide(mCurrentFragment);
            transaction.show(targetFragment);
        }
        mCurrentFragment = targetFragment;
        transaction.commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (UserManager.getUserManager().getUser() == null) {
            ARouter.getInstance().build(ArouterPath.LOGIN_ACTIVITY).navigation();
            finish();
        } else {
            setAlias();//极光的

            if (requestedOrdersSelect) {
                requestedOrdersSelect = false;
                if (mCurrentFragment != mOrdersFragment) {
                    mVDBinding.rbOrders.toggle();
                }
            } else if (requestedPayOrdersSelect) {
                requestedPayOrdersSelect = false;
                if (mCurrentFragment != mPayOrdersFragment) {
                    mVDBinding.rbPayOrders.toggle();//比 check好用   不会多次调用  导致fragment is already added
                }
            }
        }
    }

    private PermissionListener mPermissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == PERMISSION_IMAGE) {
                Intent intent = new Intent(MainActivity.this, ScanActivity.class);
                startActivityForResult(intent, 0xc1);
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == PERMISSION_IMAGE) {
                PermissionUtil.with(MainActivity.this)
                        .addPermission(Manifest.permission.CAMERA)
                        .addPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                        .addPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .initPermission();
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0xc1) {
                if (data.getIntExtra(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED) == CodeUtils.RESULT_SUCCESS) {
                    String orderNo = data.getStringExtra(CodeUtils.RESULT_STRING);
                    mViewModel.getOrderByPurchaseOrderNo(orderNo);
                } else {
                    Tooast.normalInfo("扫描失败");
                }
            }
        }
    }

    private boolean requestedOrdersSelect = false;
    private boolean requestedPayOrdersSelect = false;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LiveDataEvent liveDataEvent) {
        switch (liveDataEvent.what) {
            case BasicConstants
                    .EVENT_LOGIN_STATUS:
                ARouter.getInstance().build(ArouterPath.LOGIN_ACTIVITY).navigation();
                ActivityManager.getInstance().finishAllActivity();
                break;
            case BasicConstants
                    .EVENT_SELECT_ORDER_ALL:
                requestedOrdersSelect = true;
                break;
            case BasicConstants
                    .EVENT_SELECT_PAY_ORDER:
                requestedPayOrdersSelect = true;
                break;
        }
    }

    long last;

    @Override
    public void onBackPressed() {
        long c = System.currentTimeMillis();
        if (c - last > 1000) {
            last = c;
            Tooast.normalInfo("双击退出");
        } else {
            ActivityManager.getInstance().finishAllActivity();
        }
    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }


    private void setAlias() {
//        JPushInterface.setAlias(App.getApplication(), 1, alias);
        // 调用 Handler 来异步设置别名
        if (UserManager.getUserManager().isSetedAlias()) {
            Loog.d("MainActivity", "用户" + UserManager.getUserManager().getUser().getRealName() + "," + UserManager.getUserManager().getUser().getId() + "已设置过Alias");
        } else {
            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS));
        }
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        String logs = "--";

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            switch (code) {
                case 0:
                    logs = "Set  alias success . alias = " + alias;
                    Log.i("MainActivity", logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    UserManager.getUserManager().setedAlias();
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 10s.";
                    Log.i("MainActivity", logs);
                    // 延迟 10 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS), 1000 * 10);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e("MainActivity", logs);
            }
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    if (UserManager.getUserManager().getUser() != null) {//这里再作判断  防止进入6002 循环

                        String alias = UserManager.getUserManager().getUser().getEmpId() + "";

                        Loog.d("MainActivity", "Set alias in handler. msg.obj = " + alias);
                        // 调用 JPush 接口来设置别名。
                        JPushInterface.setAlias(getApplicationContext(),
                                alias,
                                mAliasCallback);
                    }
                    break;
                default:
                    Log.i("MainActivity", "Unhandled msg - " + msg.what);
            }
        }
    };
}
